package com.cnooc.aicv.lmapp.util;

import okhttp3.OkHttpClient;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsUtil {

    // 创建一个信任所有证书的X509TrustManager
    private static final TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }
        }
    };

    // 创建一个忽略主机名的HostnameVerifier
    private static final HostnameVerifier hostnameVerifier = (hostname, session) -> true;

    // 创建OkHttpClient实例
    public static OkHttpClient.Builder getUnsafeOkHttpClient() {
        try {
            // 安装所有信任的证书
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            return new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                .hostnameVerifier(hostnameVerifier);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 创建安全的OkHttpClient实例
    public static OkHttpClient.Builder getOkHttpClient() {
        return new OkHttpClient.Builder();
    }
}